﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AgilePlannerDT.ThirdPartySync;
using AgilePlannerDT.Data;
using Microsoft.TeamFoundation.Client;
using System.Net;
using AgilePlannerDT.Persister;

namespace AgilePlannerDT.Application.Commands.Impl
{
    class SyncronizeCommand
    {
        Project was = null;
        String collectionURI = "";
        Priority priority = Priority.AgilePlanner;
        ICredentialsProvider credProvider;
        AsynchronousPersister persister;

        public SyncronizeCommand(AsynchronousPersister persister, String url, String user, String password, Priority priority)
        {
            this.persister = persister;
            collectionURI = url;
            credProvider = new SimpleCredentialsProvider(user, password);
            this.priority = priority;
        }

        public void execute()
        {
            Project proj = persister.Project;
            TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(collectionURI), credProvider);
            
            Sync sync = new Sync(proj);
            was = (Project)proj.Clone();
            ISyncronizer syncronizer = new TFSSyncronizer(proj, tfs);
            sync.syncronize(syncronizer, priority);
            uploadToServer(proj);
        }

        private void uploadToServer(Project project)
        {
            persister.UpdateProject(project);
        }

    }

    class SimpleCredentialsProvider : ICredentialsProvider{
        public String User {get; private set;}
        public String Password {get; private set;}

        public SimpleCredentialsProvider(String user, String pass){
            User = user;
            Password = pass;
        }

        public ICredentials GetCredentials(Uri uri, ICredentials failedCredentials)
        {
            return new NetworkCredential(User, Password);
        }

        public void NotifyCredentialsAuthenticated(Uri uri)
        {
        }
    }
}
